package com.tx.admin.exception;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tx.admin.controller.vo.EntityVo;
import com.tx.admin.controller.vo.SuperVo;

@ControllerAdvice  
public class ExceptionController {

    
    @ExceptionHandler(value = {UnknownAccountException  .class}) 
   @ResponseBody
    public SuperVo UnknownAccountException  (final UnknownAccountException   ex, final HttpServletRequest req,final HttpServletResponse resp) {  
    	ex.printStackTrace();
    	resp.setStatus(601);

    	SuperVo vo =new SuperVo();
    	vo.setMsg(ex.getMessage());
    	return vo;
    }
    

    @ExceptionHandler(value = {Exception.class}) 
    @ResponseBody
    public SuperVo Exception(final Exception ex, final HttpServletRequest req,final HttpServletResponse resp) {  
    	ex.printStackTrace();
    	resp.setStatus(600);
  

    	SuperVo vo =new SuperVo();
    	vo.setMsg(ex.getMessage());
    	return vo;
    }
    
    
    @ExceptionHandler(value = {UnauthenticatedException.class}) 
    @ResponseBody
    public SuperVo UnauthenticatedException(final UnauthenticatedException ex, final HttpServletRequest req,final HttpServletResponse resp) {  
    	ex.printStackTrace();
    	resp.setStatus(600);
    	SuperVo vo =new SuperVo();
    	vo.setMsg("请登陆！");
    	return vo;
    }
    @ExceptionHandler(value = {MethodArgumentNotValidException.class}) 
    @ResponseBody
    public SuperVo Exception(final MethodArgumentNotValidException ex, final HttpServletRequest req,final HttpServletResponse resp) {  
    	ex.printStackTrace();
    	resp.setStatus(600);
    	HashMap<String,Object> map =new HashMap<>();

    	ex.getBindingResult().getFieldErrors().forEach(val -> {
    		map.put(val.getField(),val.getDefaultMessage());
    	});

    	EntityVo vo =new EntityVo<>();
    	vo.setMsg("参数校验异常");
    	vo.setEntity(map);
    	return vo;
    }
    
    
}
